package org.luxor.common.netty.jdk.aio.server.handler;

import org.luxor.commons.core.utils.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * 响应 客户端消息
 *
 * @author Mr.yan @date 2023/9/3
 */
public class ServerWriteCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {
    private static final Logger log = LoggerFactory.getLogger(ServerWriteCompletionHandler.class);

    private AsynchronousSocketChannel channel;

    public ServerWriteCompletionHandler(AsynchronousSocketChannel channel) {
        if (channel != null) {
            this.channel = channel;
        }
    }

    @Override
    public void completed(Integer result, ByteBuffer buffer) {
        // 如果有没完整写入完成，继续写入
        if (buffer.hasRemaining()) {
            channel.write(buffer, buffer, this);
        }
    }


    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        log.error("向对端写入消息，失败", exc);
        IoUtils.closeQuietly(channel);
    }
}
